package com.example.listviewcontacts;

import java.io.UnsupportedEncodingException;

import org.doubango.ngn.NgnEngine;
import org.doubango.ngn.events.NgnEventArgs;
import org.doubango.ngn.events.NgnInviteEventArgs;
import org.doubango.ngn.events.NgnMessagingEventArgs;
import org.doubango.ngn.events.NgnRegistrationEventArgs;
import org.doubango.ngn.media.NgnMediaType;

import org.doubango.ngn.services.INgnConfigurationService;
import org.doubango.ngn.services.INgnSipService;
import org.doubango.ngn.sip.NgnAVSession;

import org.doubango.ngn.sip.NgnInviteSession.InviteState;
import org.doubango.ngn.utils.NgnConfigurationEntry;
import org.doubango.ngn.utils.NgnContentType;
import org.doubango.ngn.utils.NgnStringUtils;
import org.doubango.ngn.utils.NgnUriUtils;

import org.doubango.tinyWRAP.tdav_codec_id_t;
import org.doubango.tinyWRAP.tmedia_t140_data_type_t;

import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.tv.TvContract.Programs;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.provider.SyncStateContract.Constants;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView;

public class MainActivity extends ActionBarActivity {

	private BroadcastReceiver mSipBroadCastRecv;
	private BroadcastReceiver mCallStateRecv;
	private BroadcastReceiver mMessageRecv;
	private NgnEngine mEngine;
	private INgnConfigurationService mConfigurationService;
	private INgnSipService mSipService;

	private final static String SIP_DOMAIN = "sip2sip.info";
	private final static String SIP_USERNAME = "halenaz";
	private final static String SIP_PASSWORD = "hsynrglmz";
	private final static String SIP_SERVER_HOST = "proxy.sipthor.net";
	private final static int SIP_SERVER_PORT = 5060;

	public final static String EXTRAT_SIP_SESSION_ID = "SipSession";

	private static final String TAG = "com.example.listviewcontacts.DEBUG";
	Context myContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		/*
		 * ContentValues values = new ContentValues();
		 * values.put(ContactInfoContentProvider.SIP, "hngulmez@hotmail.com");
		 * values.put(ContactInfoContentProvider.NAME, "zeynep");
		 * values.put(ContactInfoContentProvider.SURNAME, "gulmez");
		 * values.put(ContactInfoContentProvider.KEY, "zeynep"); Uri uri =
		 * getContentResolver().insert( ContactInfoContentProvider.CONTENT_URI,
		 * values); if (uri != null) Toast.makeText(getBaseContext(),
		 * uri.toString(), Toast.LENGTH_LONG) .show();
		 */

		mEngine = NgnEngine.getInstance();
		Log.d(TAG, "2");
		mConfigurationService = mEngine.getConfigurationService();
		Log.d(TAG, "3");
		mSipService = mEngine.getSipService();
		Log.d(TAG, "4");

		mSipBroadCastRecv = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				final String action = intent.getAction();

				if (NgnRegistrationEventArgs.ACTION_REGISTRATION_EVENT
						.equals(action)) {
					NgnRegistrationEventArgs args = intent
							.getParcelableExtra(NgnEventArgs.EXTRA_EMBEDDED);
					if (args == null) {
						Toast.makeText(MainActivity.this,
								"Invalid Event Argumani", Toast.LENGTH_LONG)
								.show();

						return;
					}
					switch (args.getEventType()) {
					case REGISTRATION_NOK:
						Toast.makeText(MainActivity.this,
								"Registration Failed", Toast.LENGTH_LONG)
								.show();
						break;
					case UNREGISTRATION_OK:
						Toast.makeText(MainActivity.this,
								"Unregistration Successful", Toast.LENGTH_LONG)
								.show();
						break;
					case REGISTRATION_OK:

						Toast.makeText(MainActivity.this,
								"Registration Successful", Toast.LENGTH_LONG)
								.show();
						break;
					case REGISTRATION_INPROGRESS:
						Toast.makeText(MainActivity.this, "Registering...",
								Toast.LENGTH_LONG).show();

						break;
					case UNREGISTRATION_INPROGRESS:
						Toast.makeText(MainActivity.this, "Unregistering...",
								Toast.LENGTH_LONG).show();
						break;
					case UNREGISTRATION_NOK:
						Toast.makeText(MainActivity.this,
								"Unregistration Failed", Toast.LENGTH_LONG)
								.show();
						break;
					}

				}

			}
		};

		final IntentFilter intentFilter = new IntentFilter();
		intentFilter
				.addAction(NgnRegistrationEventArgs.ACTION_REGISTRATION_EVENT);
		registerReceiver(mSipBroadCastRecv, intentFilter);

		mCallStateRecv = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				final String action = intent.getAction();
				if (NgnInviteEventArgs.ACTION_INVITE_EVENT.equals(action)) {
					NgnInviteEventArgs args = intent
							.getParcelableExtra(NgnEventArgs.EXTRA_EMBEDDED);
					if (args == null) {
						Log.d(TAG, "Invalid Event args");
						return;
					}
					NgnAVSession avSession = NgnAVSession.getSession(args
							.getSessionId());
					if (avSession == null)
						return;
					final InviteState callState = avSession.getState();
					NgnEngine mEngine = NgnEngine.getInstance();

					switch (callState) {
					case NONE:

						break;
					case INCOMING:
						Toast.makeText(context, "Incoming call",
								Toast.LENGTH_SHORT).show();

						mEngine.getSoundService().startRingTone();

						Intent i = new Intent(context.getApplicationContext(),
								CevapEkrani.class);
						i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						i.putExtra("SIP_SESSION_ID", avSession.getId());
						i.putExtra("PHONE_NUMBER_EXTRA",
								avSession.getRemotePartyDisplayName());
						context.startActivity(i);
						break;
					case INCALL:
						Toast.makeText(context, "Call Connected",
								Toast.LENGTH_SHORT).show();
						mEngine.getSoundService().stopRingTone();
						break;
					case TERMINATED:
						Toast.makeText(context, "Call Terminated",
								Toast.LENGTH_SHORT).show();
						mEngine.getSoundService().stopRingTone();
						mEngine.getSoundService().stopRingBackTone();
						break;

					default:
						break;
					}

				}

			}
		};

		final IntentFilter intentRFilter = new IntentFilter();
		intentRFilter.addAction(NgnInviteEventArgs.ACTION_INVITE_EVENT);
		registerReceiver(mCallStateRecv, intentRFilter);

		mMessageRecv = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				final String action = intent.getAction();
				if (NgnMessagingEventArgs.ACTION_MESSAGING_EVENT.equals(action)) {
					NgnMessagingEventArgs args = intent
							.getParcelableExtra(NgnEventArgs.EXTRA_EMBEDDED);
					if (args == null) {
						Log.d("Mesaj Debug", "Arguman null geldi");
						return;
					}
					switch (args.getEventType()) {
					case INCOMING: {
						if (NgnStringUtils.equals(args.getContentType(),
								NgnContentType.T140COMMAND, true)) {
							tmedia_t140_data_type_t dataType = (tmedia_t140_data_type_t) intent
									.getSerializableExtra(NgnMessagingEventArgs.EXTRA_T140_DATA_TYPE);
							switch (dataType) {
							case tmedia_t140_data_type_backspace:
								// int length =
								// mTextView_History.getEditableText().length();
								if (length > 0) {
									// mTextView_History.getEditableText().delete(length
									// - 1, length);
								}
								break;
							case tmedia_t140_data_type_cr:
							case tmedia_t140_data_type_cr_lf:
								// mTextView_History.getEditableText().append("\n");
								break;
							default:
								break;
							}
						} else { // display any other content type (e.g
									// plain/text, xml, pdf...) "AS IS"
							byte[] contentBytes = args.getPayload();
							if (contentBytes != null && contentBytes.length > 0) {
								try {
									String contentStr = new String(
											contentBytes, "UTF-8");
									// mTextView_History.getEditableText().append(contentStr);
								} catch (UnsupportedEncodingException e) {
									Log.e(TAG, e.toString());
								}
							}
						}
						break;
					}
					default: {
						break;
					}
					}
				}

			}
		};

		final IntentFilter intentMFilter = new IntentFilter();
		intentMFilter
				.addAction(NgnRegistrationEventArgs.ACTION_REGISTRATION_EVENT);
		intentMFilter.addAction(NgnInviteEventArgs.ACTION_INVITE_EVENT);
		intentMFilter.addAction(NgnMessagingEventArgs.ACTION_MESSAGING_EVENT);
		registerReceiver(mMessageRecv, intentMFilter);

	}

	@Override
	protected void onDestroy() {
		if (mEngine.isStarted()) {
			mEngine.stop();
		}
		// release the listener
		if (mSipBroadCastRecv != null) {
			unregisterReceiver(mSipBroadCastRecv);
			mSipBroadCastRecv = null;
		}
		super.onDestroy();
	}

	@Override
	protected void onResume() {

		super.onResume();
		if (!mEngine.isStarted()) {
			if (mEngine.start()) {
				Toast.makeText(getApplicationContext(), "Engine Started",
						Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(getApplicationContext(), "Engine Not Started",
						Toast.LENGTH_LONG).show();

			}
		}
		// Register
		if (mEngine.isStarted()) {
			if (!mSipService.isRegistered()) {
				// Set credentials
				mConfigurationService.putString(
						NgnConfigurationEntry.IDENTITY_IMPI, SIP_USERNAME);
				mConfigurationService.putString(
						NgnConfigurationEntry.IDENTITY_IMPU,
						String.format("sip:%s@%s", SIP_USERNAME, SIP_DOMAIN));
				mConfigurationService.putString(
						NgnConfigurationEntry.IDENTITY_PASSWORD, SIP_PASSWORD);
				mConfigurationService.putString(
						NgnConfigurationEntry.NETWORK_PCSCF_HOST,
						SIP_SERVER_HOST);
				mConfigurationService.putInt(
						NgnConfigurationEntry.NETWORK_PCSCF_PORT,
						SIP_SERVER_PORT);
				mConfigurationService.putString(
						NgnConfigurationEntry.NETWORK_REALM, SIP_DOMAIN);

				mConfigurationService.putInt(
						NgnConfigurationEntry.MEDIA_CODECS,
						tdav_codec_id_t.tdav_codec_id_pcma.swigValue()
								| tdav_codec_id_t.tdav_codec_id_pcmu
										.swigValue()
								| tdav_codec_id_t.tdav_codec_id_red.swigValue()
								| tdav_codec_id_t.tdav_codec_id_t140
										.swigValue());

				// VERY IMPORTANT: Commit changes
				mConfigurationService.commit();
				// register (log in)
				// mSipService.register(this);
			}
		}

	}

	void connectServer() {

		if (mEngine.isStarted()) {
			if (!mSipService.isRegistered()) {

				mSipService.register(this);

			} else {
				Toast.makeText(getApplicationContext(),
						"You have already registered", Toast.LENGTH_SHORT)
						.show();
			}
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.action_settings:

			break;
		case R.id.connect_server:
			connectServer();
			break;
		default:
			break;
		}

		return true;
	}

	boolean makeVoiceCall(String phoneNumber) {
		final String validUri = NgnUriUtils.makeValidSipUri(String.format(
				"sip:%s@%s", phoneNumber, SIP_DOMAIN));
		if (validUri == null) {
			// mTvLog.setText("failed to normalize sip uri '" + phoneNumber +
			// "'");
			return false;
		}
		NgnAVSession avSession = NgnAVSession.createOutgoingSession(
				mSipService.getSipStack(), NgnMediaType.Audio);
		
		
		Intent i = new Intent(getApplicationContext(), AramaEkrani.class);

		i.putExtra(EXTRAT_SIP_SESSION_ID, avSession.getId());
		
		startActivity(i);

		return avSession.makeCall(validUri);
	}

}
